import React from 'react'
import { Table,Icon,Modal,Popconfirm,Form,Input,Row,Col,DatePicker,Button,Message,Select} from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
import api from '../../../api/advRelease';
import officeApi from '../../../api/office';
import EditForm from '../../Form/AdvOutRelease';
import PageLog from '../../Form/AdPageLog';
import {uuid} from "../../../utils";

const { RangePicker } = DatePicker;
import moment from 'moment';

import PanelBox from '../../../components/PanelBox';
import {jsonToTree} from '../../../utils/tools'

import '../../../style/antd-theme.less';

export default class TablePage extends React.Component {
  state = {
    userSession:'',
    data: [],
    pagination: {
      pageSize:20,
      pageNum:1,
    },
    loading: false, 
    rowRecord:'',
    payment:{
      payMo:0,
      isOpen:false,
    },
    pageLog:{
      isOpen:false,
      logRowId:''
    },
    officeList:[]
  };
  columns = [{
    title: '广告标题',
    dataIndex: 'title',
  },{
    title: '播放类型',
    dataIndex: 'reward',
    width: '10%',
    render:(text, record, index) =>  {
      switch(record.reward){
        case 1:
          return '轮播';
        case 2:
         return '精准';
        default:
          return '未知';
      }
    },
  },{
    title: '总天数 ',
    dataIndex: 'allDays',
    width: '10%',
  },{
    title: '支付金额',
    dataIndex: 'payMo',
    width: '10%',
  },{
    title: '审核状态',
    dataIndex: 'examState',
    width: '11%',
    render:(text, record, index) =>  {
      switch(record.examState){
        case 1:
          return '待审核';
        case 2:
         return '通过';
        case 3:
         return '拒绝';
        case 0:
         return '临时';
        default:
          return '未付款';
      }
    },
  },{
    title: '接受状态',
    dataIndex: 'state',
    width: '11%',
    render:(text, record, index) =>  {
      switch(record.state){
        case 1:
          return '待接受';
        case 2:
         return '通过';
        case 3:
         return '拒绝';
        case 0:
         return '临时';
        default:
          return '未知';
      }
    },
  },{
    title: '创建时间',
    dataIndex: 'createDate',
    width: '15%',
  }, {
    title: '操作',
    key: 'action',
    width: '15%',
    render: (text, record) => (
      <span>
        <a href="javascript:void(0)" onClick={this.edit.bind(this, record)}>详情</a>
        <span className="ant-divider" />
        {/*
        <Popconfirm title="您是否要删除该记录?" onConfirm={this.delete.bind(this, record.id)} okText="是" cancelText="否">
          <a href="javascript:void(0)">删除</a>
        </Popconfirm>
        <span className="ant-divider" />
        { record.payState == 1 ?
        <a href="javascript:void(0)" onClick={this.pay.bind(this, record)}>支付</a>
        : ''}*/}
        { record.examState == 2 ?
        <a href="javascript:void(0)" onClick={this.openPageLog.bind(this, record.id)}>观看日志</a>
        : ''}
      </span>
    ),
  }];

  handleTableChange = (pagination, filters, sorter) => {
    pagination.pageNum=pagination.current;
    this.setState({pagination});
   
    this.fetch({...pagination});
  }
  fetch = (params) => {
    this.setState({ loading: true });
    params['queryType']=2;
    api.get('/advRelease/getAll', { params}).then((data) => {
      const _data = data.data.list;
      const pagination = { ...this.state.pagination };
      pagination.total = data.data.total;
      this.setState({
        loading: false,
        data: _data,
        pagination,
      });
    });
  }

  componentDidMount = () =>{
    let user =this.props.profile.user;
    this.setState({
      userSession:user
      });
    this.fetch({ ...this.state.pagination });
    this.getChildOffice(user);
  }

  getChildOffice = (user) => {
    officeApi.get('/office/findAllOfficeByType',{
      parent_id:user.officeId,
      type:'1,2'
    }).then((data) => {
        let result=data.data;
        if(result.code==0){
          let list =result.data;
          let children=[];
          children.push(<Option key={user.officeId} >{user.officeName}</Option>);
          if(list){
            list.forEach(function(value, index, array) {
              children.push(<Option key={value.id} >{value.name}</Option>);
            })
          }
          this.setState({ officeList:children});
        }
      });
    } 

  add = () => {
    if(this.resetFields)this.resetFields();
    this.setState({
      isOpenModal: true,
      clearForm: false,
      titleName: '添加广告',
      rowRecord:false,
    });
  }
  edit = (record, event) => {
    if(this.resetFields)this.resetFields();
    api.get('/adv/getAdvById', {id:record.id} ).then((data) => {
      const _data = data.data;
      let photosList=[];
      let phos="";
      if(record.photos){
         phos=JSON.parse(record.photos);
       for(let i=0;i<phos.length;i++){
          photosList.push({uid: uuid(),url:phos[i]});
        }
        _data.photos=phos;
        _data.photosList=photosList;
      }

      let voiceList=[];
      let voice="";
      if(record.voice){
        voice=JSON.parse(record.voice);
       for(let i=0;i<voice.length;i++){
          voiceList.push({uid: uuid(),name: voice[i],url:voice[i]});
        }
        _data.voiceList=voiceList;
      }

      let timeDef="";
      if( record && record.startDate && record.endDate){
        timeDef=[moment(record.startDate , "YYYY-MM-DD"), moment(record.endDate, "YYYY-MM-DD")];
        _data.timeDef=timeDef;
      }

      _data.examState=2;
      this.setState({
        isOpenModal: true,
        clearForm: false,
        titleName: '查看广告/不可修改',
        rowRecord: _data 
      });
    });
    
  }
  pay = (record, event) => {
    api.get('/office/queryWallet',{} ).then((data) => {
      const result = data.data;
      if(result.code == 0){
        const payment=this.state.payment;
        payment.isOpen=true;
        payment.payMo=record.allPlatformMo;
        payment.id=record.id;
        payment.balance =result.data.balance;
        this.setState({payment});
       }else{
        Message.error(result.message);
       }
    });
    
  }
  
  delete = (id,event) => {
    api.delete('/advRelease/delete', {id:id}).then((data) => {
      const result= data.data;
     if(result.code == 0){
      Message.success('删除成功！');
      this.fetch({ ...this.state.pagination });
     }else{
      Message.error(result.message);
     }
    });
  }
  openPageLog = (id, event) => {
    let pageLog=this.state.pageLog;
    pageLog.isOpen=true;
    pageLog.logRowId=id;
    this.setState({pageLog});
    
  }
  close = () => {
    this.setState({
      isOpenModal: false,
      clearForm: true,
    });
  }
  refeshData = () => {
    this.fetch({ ...this.state.pagination });
  }

  initChildrenParams = (params) => {
    this.resetFields = params.resetFields;
  }
  payment={
    closeModal:()=>{
      const payment=this.state.payment;
      payment.isOpen=false;
      this.setState({payment});
    },
    pay:(id, event) => {
      api.get('/adv/advScreenInfo/pay',{params: {id:id}} ).then((data) => {
        const result = data.data;
        if(result.code == 0){
          Message.success('支付成功！');
          this.payment.closeModal();
          this.fetch({ ...this.state.pagination });
         }else{
          Message.error(result.message);
         }
      });
    },
  }
  pageLog={
    closeModal:()=>{
      const pageLog=this.state.pageLog;
      pageLog.isOpen=false;
      this.setState({pageLog});
    },
  }

  render() {
    
    return (
      <div>
        <SearchForm searchCostState={this.state} goSearch={this.handleTableChange} create={this.add}/>
        <PanelBox>
          <Table columns={this.columns}  dataSource={this.state.data}  pagination={this.state.pagination}
            loading={this.state.loading}  onChange={this.handleTableChange}  rowKey='id' locale={{emptyText:'该代理商下暂无数据'}}
          />
        </PanelBox>
        <Modal
          title={this.state.titleName}
          visible={this.state.isOpenModal}
          onCancel={this.close}
          width={800}
          wrapClassName="vertical-center-modal"
          footer={null}
        >
          <EditForm userSession={this.state.userSession} rowRecord={this.state.rowRecord} pay={this.pay} close={this.close} refeshData={this.refeshData} clearForm={this.state.clearForm}  callbackParent={this.initChildrenParams}/>
        </Modal>
        <Modal
          title="支付"
          visible={this.state.payment.isOpen}
          onCancel={this.payment.closeModal}
          wrapClassName="vertical-center-modal"
          footer={null}
          >
          <div>
            <Row style={{marginBottom:'20px'}} ><Col style={{color:'red'}}>您应支付：{this.state.payment.payMo}元；</Col>&nbsp;&nbsp; <Col span={10}>(您的余额为：{this.state.payment.balance}元；)</Col></Row>
            <Button type="primary"  size="large" style={{marginRight:'10px'}}  onClick={this.payment.pay.bind(this,this.state.payment.id)} >支付</Button>
            <Button onClick={this.payment.closeModal}>稍后支付</Button>
          </div>
        </Modal>
        <Modal
          title='日志'
          visible={this.state.pageLog.isOpen}
          onCancel={this.pageLog.closeModal}
          width={800}
          wrapClassName="vertical-center-modal"
          onOk={this.pageLog.closeModal}
          okText="确认"
        >
          <PageLog rowId={this.state.pageLog.logRowId} close={this.pageLog.closeModal} />
        </Modal>
      </div>
    );
  }
}

    class SearchsForm extends React.Component {
      // 开始搜索
      goSearch = (e) => {
        let params=this.props.form.getFieldsValue().search;
        let _this=this.props;
        params.pageSize=_this.searchCostState.pagination.pageSize;
        params.pageNum =1;
        params.current =1;
        _this.goSearch(params);
     
      }

      srearchStyle = {
        labelCol: { span: 8},
        wrapperCol: { span: 14 },
      };
     
      render() {
        const { getFieldDecorator } = this.props.form;
        const {create } = this.props;
        const formItemLayout = this.srearchStyle;
        return <Form onSubmit={this.goSearch} layout="inline" style={{marginBottom:'10px'}}>
        <FormItem
          {...formItemLayout}
          style={{width:'300px'}}
            label="选择代理商"
          >
          {getFieldDecorator('search.officeId',{
            initialValue:this.props.searchCostState.userSession.officeId
          } )(
            <Select
              placeholder="选择代理商"
            >
            {this.props.searchCostState.officeList || []}
            </Select>
          )}
          </FormItem>
          <FormItem {...formItemLayout} label="广告标题" style={{marginRight:0,marginBottom:'10px'}}>
            {getFieldDecorator('search.title')(
              <Input type="text" placeholder="搜索的广告标题"/>
            )}
          </FormItem>
          <FormItem>
            <Button type="primary" icon="search" htmlType="submit">搜索</Button>
          </FormItem> 
          {/*
          <FormItem>
            <Button type="primary" icon="plus" onClick={create}>发布广告</Button>
          </FormItem>*/}
        </Form>
      }
    }
    const SearchForm = Form.create({})(SearchsForm);